# @Time : 2021/4/25 10:33
# @Author : Fioman 
# @Phone : 13149920693
import os

import cv2 as cv
import numpy as np
from db_tools.db_handler import DbHandler
db = DbHandler()
from tools.config_params import ConfigParams
cp = ConfigParams()
"""
图像转换工具,图像的各种转换工具都在里面
"""

limitPosition = db.get_produce_limit_position()
# 机械手坐标的极限位置:
ROBOT_LIMIT_X_MIN = limitPosition.get("ROBOT_LIMIT_X_MIN", 430)  # 机械手坐标X的最小值
ROBOT_LIMIT_X_MAX = limitPosition.get("ROBOT_LIMIT_X_MAX", 770)  # 机械手坐标X的最大值
ROBOT_LIMIT_Y_MIN = limitPosition.get("ROBOT_LIMIT_Y_MIN", -600)  # 机械手坐标Y的最小值
ROBOT_LIMIT_Y_Max = limitPosition.get("ROBOT_LIMIT_Y_Max", -190)  # 机械手坐标Y的最大值


def get_joint_image(leftImage, rightImage):
    """
    根据拼接的参数,获取两张图的拼接之后的图像
    :param leftImage:
    :param rightImage:
    :return:
    """
    res, imageJointParams = db.get_image_joint_params()
    if res == "ok":
        leftCamStartOffset = int(imageJointParams.get("leftCamStartOffset"))  # 左相机的左边截掉的像素数
        leftCamEndOffset = int(imageJointParams.get("leftCamEndOffset"))  # 左相机右边截掉的像素数
        rightCamStartOffset = int(imageJointParams.get("rightCamStartOffset"))  # 右相机左边截掉的像素数
        rightCamEndOffset = int(imageJointParams.get("rightCamEndOffset"))  # 右相机右边截掉的像素数
        leftCamHOffset = int(imageJointParams.get("leftCamHOffset"))  # 左相机的高度移动的像素数,负数表示上移,正数表示向下移动
        print("leftImage = {},rightImage = {}".format(leftImage.shape[:2], rightImage.shape[:2]))
        leftImage = leftImage[:, leftCamStartOffset:(leftImage.shape[1] - leftCamEndOffset)]
        rightImage = rightImage[:, rightCamStartOffset:(rightImage.shape[1] - rightCamEndOffset)]

        # 检测高度是否变化
        newLeftImage = np.zeros(leftImage.shape, dtype=np.uint8)
        if leftCamHOffset < 0:  # 向上移动
            newLeftImage[:(leftImage.shape[0] - abs(leftCamHOffset))] = leftImage[abs(leftCamHOffset):]
        elif leftCamHOffset > 0:  # 向下移动
            newLeftImage[leftCamHOffset:] = leftImage[:(leftImage.shape[0] - leftCamHOffset)]
        else:
            newLeftImage = leftImage
        # 拼接图像
        jointImage = np.hstack((newLeftImage, rightImage))
        jointImage = cv.resize(jointImage, (jointImage.shape[1], int(jointImage.shape[0] * cp.heightWidthRatio)), interpolation=cv.INTER_AREA)
        print("jointImage = {}".format(jointImage.shape[:2]))
        return jointImage
    else:
        return None


def flip_image(imageSrc, flipAxis):
    """
    图像翻转
    :param imageSrc:原图
    :param flipAxis: 翻转的轴
    :return:
    """
    if flipAxis == "x" or flipAxis == "X":
        flipped = cv.flip(imageSrc, 1)
    elif flipAxis == "y" or flipAxis == "Y":
        flipped = cv.flip(imageSrc, 0)
    else:
        flipped = cv.flip(imageSrc, -1)
    return flipped

def get_image_used(image):
    """
    获取旋转截取后的图片,将原来的图片进行处理一下
    :param image:
    :return:
    """
    newImage = rotate_image_no_scale(image,90)  # 逆时针旋转90度.
    yStart,yEnd,xStart,xEnd = [589,3000,123,2023]
    newImage = newImage[yStart:yEnd,xStart:xEnd]
    return newImage


def rotate_image_no_scale(imageSrc, rotateAngle):
    """
    无缩放的旋转图像的逻辑.旋转后的宽是原来的高,旋转后的高是原来的宽.
    :param imageSrc:要旋转的图片
    :param rotateAngle:旋转的角度,顺时针为负,逆时针为正.
    :return:返回旋转之后的图片
    """
    if len(imageSrc.shape) >= 3:
        # 先转换为灰度图
        imageSrc = cv.cvtColor(imageSrc, cv.COLOR_BGR2GRAY)

    height, width = imageSrc.shape[:2]
    # 根据旋转角度获取旋转矩阵
    if width > height:
        paddingSize = (width - height) // 2
        sizeUsed = (width, width)
        rotateCenter = (sizeUsed[0] // 2, sizeUsed[1] // 2)
        imagePadded = np.zeros(sizeUsed, dtype=np.uint8)
        imagePadded[paddingSize:paddingSize + height, :] = imageSrc
        rotatedM = cv.getRotationMatrix2D(rotateCenter, rotateAngle, 1.0)
        imageRotated = cv.warpAffine(imagePadded, rotatedM, sizeUsed)
        image_show("Rotated", imageRotated)
        imageWithoutPadding = imageRotated[:, paddingSize:height + paddingSize]
    else:
        paddingSize = (height - width) // 2
        sizeUsed = (height, height)
        rotateCenter = (sizeUsed[0] // 2, sizeUsed[1] // 2)
        imagePadded = np.zeros(sizeUsed, dtype=np.uint8)
        imagePadded[:, paddingSize:paddingSize + width] = imageSrc
        rotatedM = cv.getRotationMatrix2D(rotateCenter, rotateAngle, 1.0)
        imageRotated = cv.warpAffine(imagePadded, rotatedM, sizeUsed)
        imageWithoutPadding = imageRotated[paddingSize:width + paddingSize, :]
    return imageWithoutPadding


def image_show(name, image, showState=False):
    """
    显示图片
    :param name: 要显示的窗口文件名称
    :param image: 显示的图像
    :param showState:是否显示的标志位
    :return:
    """
    if showState:
        scale = 4
        height, width = image.shape[:2]
        newWidth, newHeight = width // scale, height // scale
        imageShow = cv.resize(image, (newWidth, newHeight), cv.INTER_AREA)
        cv.namedWindow("{}".format(name))
        cv.imshow("{}".format(name), imageShow)
        cv.waitKey(0)


if __name__ == '__main__':
    filePath = r"D:\shenghong\cutter_raw\8607--time2021-05-08_01-55-15--end--cam1.bmp"
    newImageKeepDir = r"D:\mingyang\rotated"
    if not os.path.exists(newImageKeepDir):
        os.makedirs(newImageKeepDir)
    imageSrc = cv.imread(filePath, cv.IMREAD_GRAYSCALE)
    imageRotated = rotate_image_no_scale(imageSrc, 90)
    os.remove(filePath)
    cv.imwrite(filePath, imageRotated)
